/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.server.html.model;

import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 *
 * @author Walter L�tgenau
 */
public class EmptyParametersHttpRequestWrapper extends HttpServletRequestWrapper implements HttpServletRequest {
    HashSet<String> allowedParameters = new HashSet<String>();

    /**
     * Wrap the request. No parameters shall be visible.
     * 
     * @param request
     */
    public EmptyParametersHttpRequestWrapper(HttpServletRequest request) {
        this(request, null);
    }

    /**
     * Wrap the request, make visible only the parameter names provided
     *
     * @param request
     * @param allowedParameters these parameters shall be visible, all others not
     */
    public EmptyParametersHttpRequestWrapper(HttpServletRequest request, String[] allowedParameters) {
        super(request);
        if (allowedParameters == null)
            this.allowedParameters = new HashSet<String>();
        else
            this.allowedParameters = new HashSet<String>(Arrays.asList(allowedParameters));
    }

    @Override
    public String getParameter(String name) {
        if (allowedParameters.contains(name))
            return super.getParameter(name);
        return null;
    }

    @Override
    public Map getParameterMap() {
        HashMap result = new HashMap();
        for (String allowedParameter : allowedParameters) {
            if (super.getParameter(allowedParameter) != null)
                result.put(allowedParameter, super.getParameter(allowedParameter));
        }

        return result;
    }

    @Override
    public Enumeration getParameterNames() {
        return Collections.enumeration(allowedParameters);
    }

    @Override
    public String[] getParameterValues(String name) {
        if (allowedParameters.contains(name))
            return super.getParameterValues(name);
        return null;

    }

}
